<?php

/*
+--------------------------------------------------------------------------
|   Invision Power Board
|   =============================================
|   by Matthew Mecham
|   (c) 2001 - 2006 Invision Power Services, Inc.
|   
|   =============================================
|   
|   
+---------------------------------------------------------------------------
|   > $Date: 2006-08-01 17:02:55 +0100 (Tue, 01 Aug 2006) $
|   > $Revision: 425 $
|   > $Author: matt $
+---------------------------------------------------------------------------
|
|   > Personal Profile Portal Class: Diaries
|   > Module written by BabyWolf
|   > Date started: 12 April 2010
|
+--------------------------------------------------------------------------
*/

/**
* Main content
*
*/

if ( ! defined( 'IN_IPB' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
    exit();
}

class profile_diaries
{
    /**
    * Global IPSCLASS
    * @var	object
    */
    var $ipsclass;

    /*-------------------------------------------------------------------------*/
    // Return data
    /*-------------------------------------------------------------------------*/
	
    /**
	* Returns a block of HTML back to the ajax handler
	* which then replaces the inline content with the HTML
	* returned.
	*
	*/
    function return_html_block( $member=array() ) 
    {
            //-----------------------------------------
            // INIT
            //-----------------------------------------

            $content   = '';
            $forum_ids = array();

            //-----------------------------------------
            // Skin set loaded?
            //-----------------------------------------

            if ( ! is_object( $this->ipsclass->compiled_templates['skin_profile'] ) )
            {
                    $this->ipsclass->load_template( 'skin_profile' );
            }

            $this->ipsclass->load_language( 'lang_topic' );

            //-----------------------------------------
            // Got a member?
            //-----------------------------------------

            if ( ! is_array( $member ) OR ! count( $member ) )
            {
                    return $this->ipsclass->compiled_templates['skin_profile']->personal_portal_no_content( 'err_no_posts_to_show' );
            }

            if( !$this->ipsclass->member['g_other_topics'] AND $this->ipsclass->member['id'] != $member['id'] )
            {
                    return $this->ipsclass->compiled_templates['skin_profile']->personal_portal_no_content( 'err_no_posts_to_show' );
            }

            //-----------------------------------------
            // Allowed forums...
            //-----------------------------------------

            $forum_ids = $this->ipsclass->forums->forums_get_all_allowed_forum_ids( 'read_perms' );

            //-----------------------------------------
            // Remove trash can...
            //-----------------------------------------

            if ( $this->ipsclass->vars['forum_trash_can_id'] )
            {
                    unset( $forum_ids[ $this->ipsclass->vars['forum_trash_can_id'] ] );
            }

            //-----------------------------------------
            // Check.. Again...
            //-----------------------------------------

            if ( ! is_array( $forum_ids ) OR ! count( $forum_ids ) )
            {
                    return $this->ipsclass->compiled_templates['skin_profile']->personal_portal_no_content( 'err_no_posts_to_show' );
            }

            if($this->ipsclass->member['id']==$member['id']) $content = $this->ipsclass->compiled_templates['skin_profile']->new_topic_button();

            // Add switch case here by BabyWolf
            if(isset($this->ipsclass->input['tid'])) {
                    // Call view detail function for topic here
                    $content .= $this->show_diaries_detail($member, $forum_ids);
            }
            else {
                    // Call view topic list function here
                    $content .= $this->show_diaries_list($member, $forum_ids);
            }

            if ( stristr( $content, "[attachmentid=" ) )
            {
                    $content = preg_replace( "#\[attachmentid=(\d+)\]#is", "", $content );
            }		

            //-----------------------------------------
            // Macros...
            //-----------------------------------------

            if ( ! is_array( $this->ipsclass->skin['_macros'] ) OR ! count( $this->ipsclass->skin['_macros'] ) )
    {
            $this->ipsclass->skin['_macros'] = unserialize( stripslashes($this->ipsclass->skin['_macro']) );
    }

            if ( is_array( $this->ipsclass->skin['_macros'] ) )
    {
                    foreach( $this->ipsclass->skin['_macros'] as $row )
                    {
                            if ( $row['macro_value'] != "" )
                            {
                                    $content = str_replace( "<{".$row['macro_value']."}>", $row['macro_replace'], $content );
                            }
                    }
            }

            $content = str_replace( "<#IMG_DIR#>", $this->ipsclass->skin['_imagedir'], $content );
            $content = str_replace( "<#EMO_DIR#>", $this->ipsclass->skin['_emodir']  , $content );

            //-----------------------------------------
            // Return content..
            //-----------------------------------------
            return $content ? $content.$pagelink : $this->ipsclass->compiled_templates['skin_profile']->personal_portal_no_content( 'err_no_posts_to_show' );
    }
	
    function show_diaries_detail($member=array(),$forum_ids=array()) {
		
		$topic_id = intval($this->ipsclass->input['tid']);
		
		// First get topic information
		$this->ipsclass->DB->simple_construct(array('select'	=> '*',
													'from'		=> 'topics',
													'where'		=> 'starter_id='.$member['id'].' AND forum_id IN('.trim($this->ipsclass->vars['dkm_diaries_box'],",").') AND approved=1 AND tid='.$topic_id
														));
		
		$this->ipsclass->DB->simple_exec();
		
		// If there is no topic selected, display message with no content.
		$topic = $this->ipsclass->DB->fetch_row();

		if(!$topic)
			return $this->ipsclass->compiled_templates['skin_profile']->personal_portal_no_content( 'err_no_posts_to_show' );
		
		// Prepare for building url by BabyWolf
		$author_uname_noaccent = strtolower($this->ipsclass->textcode->RemoveAccent($member['name'],"-"));
		$topic_title_noaccent = strtolower(($this->ipsclass->textcode->RemoveAccent($topic['title'],"-")));
		$topic_url = $author_uname_noaccent."/diaries/".$topic_title_noaccent.".".$topic['tid'];
		$url = $this->ipsclass->vars['profile_url']."/".$topic_url;
		
		// Require topic library
		require_once( ROOT_PATH."sources/action_public/topics.php");
		$this->lib = new topics();
		$this->lib->ipsclass = &$this->ipsclass;
		
		$this->ipsclass->input['t'] = $topic_id;
		$this->lib->init();
		$this->lib->topic_set_up();

		$pagelinks = $this->ipsclass->compiled_templates['skin_profile']->personal_portal_page_link($this->lib->topic['SHOW_PAGES']);
		$url_need_to_fix = $this->ipsclass->vars['profile_url']."/".$author_uname_noaccent."/".$topic_title_noaccent.".".$topic['tid'];
		$pagelinks = str_replace($url_need_to_fix, $url, $pagelinks);
		$pagelinks = str_replace('&amp;st=',"?st=",$pagelinks);
		$content = $pagelinks;
		
		//-----------------------------------------
		// Grab the posts we'll need
		//-----------------------------------------
		$first = intval($this->ipsclass->input['st']) >=0 ? intval($this->ipsclass->input['st']) : 0;
		
		if ( $this->ipsclass->vars['post_order_column'] != 'post_date' )
		{
			$this->ipsclass->vars['post_order_column'] = 'pid';
		}
		
		if ( $this->ipsclass->vars['post_order_sort'] != 'desc' )
		{
			$this->ipsclass->vars['post_order_sort'] = 'asc';
		}
		
		//-----------------------------------------
		// Moderator?
		//-----------------------------------------
		
		$queued_query_bit = ' and queued=0';
			
		if ( $this->ipsclass->can_queue_posts($this->topic['forum_id']) )
		{
			$queued_query_bit = '';
			
			if ( isset($this->ipsclass->input['modfilter']) AND  $this->ipsclass->input['modfilter'] == 'invisible_posts' )
			{
				$queued_query_bit = ' and queued=1';
			}
		}
		
		//-----------------------------------------
		// Run query
		//-----------------------------------------

		$this->lib->topic_view_mode = 'linear';
			
		# We don't need * but if we don't use it, it won't use the correct index
		$this->ipsclass->DB->simple_construct( array (
													   'select' => 'pid,topic_id',
													   'from'   => 'posts',
													   'where'  => 'topic_id='.$topic_id. $queued_query_bit,
													   'order'  => $this->ipsclass->vars['post_order_column'].' '.$this->ipsclass->vars['post_order_sort'],
													   'limit'  => array( $first, $this->ipsclass->vars['display_max_posts'] )
											)        );
								
		$this->ipsclass->DB->simple_exec();
			
		while( $p = $this->ipsclass->DB->fetch_row() )
		{
			$this->pids[] = $p['pid'];
		}
		
		//-----------------------------------------
		// Do we have any PIDS?
		//-----------------------------------------
		
		if ( ! count( $this->pids ) )
		{
			if ( $first )
			{
				//-----------------------------------------
				// Add dummy PID, AUTO FIX
				// will catch this below...
				//-----------------------------------------
				
				$this->pids[] = 0;
			}
			
			if ( $this->ipsclass->input['modfilter'] == 'invisible_posts' )
			{
				$this->pids[] = 0;
			}
		}
		
		//-----------------------------------------
		// Fail safe
		//-----------------------------------------
		
		if ( ! is_array( $this->pids ) or ! count( $this->pids ) )
		{
			$this->pids = array( 0 => 0 );
		}
		
		//-----------------------------------------
		// Get posts
		//-----------------------------------------
		
		$this->ipsclass->DB->cache_add_query( 'topics_get_posts', array( 'pids' => $this->pids, 'scol' => $this->ipsclass->vars['post_order_column'], 'sord' => $this->ipsclass->vars['post_order_sort'] ) );
										 					 
		$oq = $this->ipsclass->DB->simple_exec();
		$count = 1;
		
		while ( $row = $this->ipsclass->DB->fetch_row( $oq ) )
		{
			$return = $this->lib->parse_row( $row );

			$poster = $return['poster'];
			
			$row    = $return['row'];
			$row['count'] = $count;
			//-----------------------------------------
			// Print post row
			//-----------------------------------------
			
			$content .= $this->ipsclass->compiled_templates['skin_profile']->RenderRow( $row, $poster );
			
			//-----------------------------------------
			// Are we giving this bloke a good ignoring?
			//-----------------------------------------
			
			if ( $this->ipsclass->member['ignored_users'] )
			{
				if ( strstr( $this->ipsclass->member['ignored_users'], ','.$poster['id'].',' ) and $this->ipsclass->input['p'] != $row['pid'] )
				{
					if ( ! strstr( $this->ipsclass->vars['cannot_ignore_groups'], ','.$poster['mgroup'].',' ) )
					{
						$content .= $this->ipsclass->compiled_templates['skin_profile']->render_row_hidden( $row, $poster );
					}
				}
			}
			$count++;
		}
		
		//-----------------------------------------
		// ATTACHMENTS!!!
		//-----------------------------------------
		
		if ( $topic['topic_hasattach'] )
		{
			if ( ! is_object( $this->class_attach ) )
			{
				//-----------------------------------------
				// Grab render attach class
				//-----------------------------------------

				require_once( ROOT_PATH . 'sources/classes/attach/class_attach.php' );
				$this->class_attach           =  new class_attach();
				$this->class_attach->ipsclass =& $this->ipsclass;
			}
			
			//-----------------------------------------
			// Not got permission to view downloads?
			//-----------------------------------------
			
			if ( $this->ipsclass->check_perms($this->ipsclass->forums->forum_by_id[ $topic['forum_id'] ]['download_perms']) === FALSE )
			{
				$this->ipsclass->vars['show_img_upload'] = 0;
			}
			
			//-----------------------------------------
			// Continue...
			//-----------------------------------------
			
			$this->class_attach->type  = 'post';
			$this->class_attach->init();
		
			$content = $this->class_attach->render_attachments( $content, $this->pids );
		}
		$content .= $pagelinks;
		
		$forum = $this->ipsclass->forums->forum_by_id[ $topic['forum_id'] ];
		
		if($_GET['test']) {
			print "<pre>";
			print_r($this->ipsclass->member);
			print "</pre>";
		}
		
		if (   ( $forum['quick_reply'] == 1 )
		   and ( $this->ipsclass->check_perms( $forum['reply_perms']) == TRUE )
		   and ( $topic['state'] != 'closed' )
		   and ( $this->ipsclass->member['id']==$member['id'] 
		   	  or $this->ipsclass->member['_cache']['friends'][$member['id']] ) )
		{
			$show = "none";
			
			$sqr = isset($this->ipsclass->member['_cache']['qr_open']) ? $this->ipsclass->member['_cache']['qr_open'] : 0;
			
			if ( $sqr == 1 )
			{
				$show = "show";
			}
		
			$content .= $this->ipsclass->compiled_templates['skin_topic']->quick_reply_box_closed();
			$content .= $this->ipsclass->compiled_templates['skin_topic']->quick_reply_box_open($topic['forum_id'], $topic['tid'], $show, $this->ipsclass->return_md5_check());
		}
		
		return $content;		
	}
	
    function show_diaries_list($member=array(),$forum_ids=array()) {
		
		$last_x    = 5;
		
		//-----------------------------------------
		// Get last X posts
		//-----------------------------------------
		// Add Pagination by BabyWolf
		$this->ipsclass->DB->simple_construct(array( 'select'   => 'COUNT(*) AS totalTopic',
		  										 'from'     => 'topics',
		  										 'where'    => 'starter_id='.$member['id'].' AND forum_id IN('.trim($this->ipsclass->vars['dkm_diaries_box'],",").') AND approved=1',
												 'order'    => 'start_date DESC',
												  ));
		$c = $this->ipsclass->DB->exec_query();
		$result = $this->ipsclass->DB->fetch_row($c);
		
		$pagelink
			= $this->ipsclass->build_pagelinks( array( 'TOTAL_POSS'  => $result['totalTopic'],
													   'PER_PAGE'    => $last_x,
													   'CUR_ST_VAL'  => $this->ipsclass->input['st'],
													   'BASE_URL'    => $this->ipsclass->profile_url.strtolower($member['name'])."/diaries/",
													 )
											  );

		$pagelink = $this->ipsclass->compiled_templates['skin_profile']->personal_portal_page_link($pagelink);
		$pagelink = str_replace('&amp;st=','?st=',$pagelink);
		
		$content = $pagelink;
		
		$this->ipsclass->DB->build_query( array( 'select'   => 't.*',
		  										 'from'     => array( 'topics' => 't' ),
		  										 'where'    => 't.starter_id='.$member['id'].' AND t.forum_id IN('.trim($this->ipsclass->vars['dkm_diaries_box'],",").') AND t.approved=1',
												 'order'    => 't.start_date DESC',
												 'limit'    => array($this->ipsclass->input['st'], $last_x ),
												 'add_join' => array( 0 => array(
																				  'select' => 'p.*',
																				  'from'   => array( 'posts' => 'p' ),
																				  'where'  => 't.topic_firstpost=p.pid',
																				  'type'   => 'inner' ) ) ) ) ;
			
		$o = $this->ipsclass->DB->exec_query();
		
		// Prepare for building url by BabyWolf
		$author_uname_noaccent = strtolower($this->ipsclass->textcode->RemoveAccent($member['name'],"-"));
		
		while( $row = $this->ipsclass->DB->fetch_row( $o ) )
		{
			if ( ! $this->ipsclass->member['view_img'] )
			{
				//-----------------------------------------
				// unconvert smilies first, or it looks a bit crap.
				//-----------------------------------------
				
				$row['post'] = preg_replace( "#<!--emo&(.+?)-->.+?<!--endemo-->#", "\\1" , $row['post'] );
				
				$row['post'] = preg_replace( "/<img src=[\"'](.+?)[\"'].+?".">/", "(IMG:<a href='\\1' target='_blank'>\\1</a>) ", $row['post'] );
			}

			$row['_post_date']  = $this->ipsclass->get_date( $row['post_date'], 'SHORT' );
			$row['_date_array'] = $this->ipsclass->date_getgmdate( $row['post_date'] + $this->ipsclass->get_time_offset() );
			
			$row['post'] .= "\n<!--IBF.ATTACHMENT_". $row['pid']. "-->";
			
			//-----------------------------------------
			// ATTACHMENTS
			//-----------------------------------------

			if ( $row['topic_hasattach'] )
			{
				if ( ! is_object( $this->class_attach ) )
				{
					//-----------------------------------------
					// Grab render attach class
					//-----------------------------------------

					require_once( ROOT_PATH . 'sources/classes/attach/class_attach.php' );
					$this->class_attach           =  new class_attach();
					$this->class_attach->ipsclass =& $this->ipsclass;
					
					$this->ipsclass->load_template( 'skin_topic' );
				}
				
				//-----------------------------------------
				// Not got permission to view downloads?
				//-----------------------------------------
				
				if ( $this->ipsclass->check_perms($this->ipsclass->forums->forum_by_id[ $row['forum_id'] ]['download_perms']) === FALSE )
				{
					$this->ipsclass->vars['show_img_upload'] = 0;
				}						
				
				$this->class_attach->type  = 'post';
				$this->class_attach->init();

				$row['post'] = $this->class_attach->render_attachments( $row['post'], array( $row['pid'] => $row['pid'] ) );
			}
			
			$topic_title_noaccent = strtolower(($this->ipsclass->textcode->RemoveAccent($row['title'],"-")));
			$topic_url = $author_uname_noaccent."/diaries/".$topic_title_noaccent.".".$row['tid'];
			$url = $this->ipsclass->vars['profile_url']."/".$topic_url;
			
			$content .= $this->ipsclass->compiled_templates['skin_profile']->personal_portal_single_column( $row, $this->ipsclass->lang['profile_read_topic'], $url, $row['title'] );
		}
		
		return $content;
	}
	
}


?>